package com.yoda.mall.mysql.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yoda.common.exception.BusinessException;
import com.yoda.common.exception.ErrorResult;
import com.yoda.common.utils.Utils;
import com.yoda.mall.api.OrderApi;
import com.yoda.mall.model.entity.oms.Order;
import com.yoda.mall.model.entity.oms.OrderItem;
import com.yoda.mall.model.entity.oms.OrderOperateHistory;
import com.yoda.mall.model.vo.OrderDetailVo;
import com.yoda.mall.model.vo.PageResult;
import com.yoda.mall.mysql.mapper.OrderItemMapper;
import com.yoda.mall.mysql.mapper.OrderMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yoda.mall.mysql.mapper.OrderOperateHistoryMapper;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author wjy
 * @date 2022年 12月 18日 15:36
 */
@DubboService
public class OrderApiImpl implements OrderApi {

    @Autowired
    private OrderMapper orderMapper;

    @Resource
    private OrderItemMapper orderItemMapper;

    @Resource
    private OrderOperateHistoryMapper orderOperateHistoryMapper;

    /**
     * 批量删除兼单个删除
     *
     * @param ids
     */
    public void deletes(List<Integer> ids) {
        //todo 逻辑删除 @author汪金雨
        orderMapper.deleteByLogic(ids);
    }

    /**
     * 查询订单
     *
     * @param pageNum
     * @param pageSize
     * @param createTime
     * @param orderType
     * @param orderSn
     * @param sourceType
     * @param status
     * @return
     */
    @Override
    public PageResult<Order> orderList(Integer pageNum, Integer pageSize,
                                       String createTime, Integer orderType,
                                       String orderSn, Integer sourceType,
                                       Integer status, String receiverKeyword) throws ParseException {
        //        1.构造分页查询构造器
        Page<Order> orderPage = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
//        2.手机和项目模糊查询
        if (StringUtils.isNotEmpty(createTime)) {
            Date createDate = Utils.stringDateFormatTransfer(createTime);
            qw.le(Objects.nonNull(createDate), Order::getCreateTime, createDate);
        }
        if (StringUtils.isNotEmpty(receiverKeyword)) {
            qw.like(Order::getReceiverName, receiverKeyword);
            qw.like(Order::getReceiverPhone, receiverKeyword);
        }

        qw.eq(Objects.nonNull(orderType), Order::getOrderType, orderType)
                .eq(StringUtils.isNotEmpty(orderSn), Order::getOrderSn, orderSn).eq(Objects.nonNull(sourceType), Order::getSourceType, sourceType)
                .eq(Objects.nonNull(status), Order::getStatus, status);
        orderMapper.selectPage(orderPage, qw);

        return new PageResult<>(pageNum, pageSize, (int) orderPage.getTotal(), orderPage.getRecords());

    }

    @Override
    public OrderDetailVo getOrderDetailById(Long id) {
        Order order = orderMapper.selectById(id);
        LambdaQueryWrapper<OrderItem> orderItemWrapper = new LambdaQueryWrapper<>();
        orderItemWrapper.eq(OrderItem::getOrderId, id);
        List<OrderItem> orderItems = orderItemMapper.selectList(orderItemWrapper);
        //根据订单id查询操作历史
        LambdaQueryWrapper<OrderOperateHistory> historyWrapper = new LambdaQueryWrapper<>();
        historyWrapper.eq(OrderOperateHistory::getOrderId,id);
        List<OrderOperateHistory> historyList = orderOperateHistoryMapper.selectList(historyWrapper);
        OrderDetailVo vo = new OrderDetailVo();
        BeanUtils.copyProperties(order, vo);
        vo.setOrderItemList(orderItems);
        vo.setHistoryList(historyList);
        return vo;
    }

    @Override
    public Integer updateOrderById(Order order,String username) {

        int count = orderMapper.updateById(order);
        OrderOperateHistory history = new OrderOperateHistory();
        history.setOrderId(order.getId());
        history.setNote(order.getNote());
        history.setOperateMan(username);
        history.setOrderStatus(order.getStatus());
        history.setCreateTime(LocalDateTime.now());
        orderOperateHistoryMapper.insert(history);
        return count;
    }

    /**
     * 批量关闭
     *
     * @param ids
     * @param note
     */
    @Override
    @Transactional
    public void updateClose(List<Long> ids, String note,String username) {
        if (ids == null) {
            return;
        }
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        qw.in(Order::getId, ids);

        List<Order> orders = orderMapper.selectList(qw);
        List<OrderOperateHistory> list = new ArrayList<>();
        for (Order order : orders) {
            //保存关闭操作记录
            OrderOperateHistory history = new OrderOperateHistory();
            history.setOrderId(order.getId());
            history.setNote(note);
            history.setOperateMan(username);
            history.setOrderStatus(4);
            history.setCreateTime(LocalDateTime.now());
            list.add(history);
            order.setStatus(4);
            order.setNote(note);
            LambdaQueryWrapper<Order> oqw = new LambdaQueryWrapper<>();
            oqw.eq(Order::getId, order.getId());
            orderMapper.update(order, oqw);
        }
        orderOperateHistoryMapper.saveBatch(list);
    }

    /**
     * 批量发货
     *
     * @return
     */
    @Override
    @Transactional
    public Integer updateDelivery(List<Order> orders,String username) {
        if (Objects.isNull(orders) || orders.size() == 0) {
            throw new BusinessException(ErrorResult.builder().errMessage("您未选中任何订单").errCode(1000).build());
        }
        List<OrderOperateHistory> list = new ArrayList<>();
        int num = 0;
        for (Order order : orders) {
            LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Order::getStatus, 1);
            wrapper.eq(Order::getId,order.getId());
            int count = orderMapper.update(order, wrapper);
            num += count;

            //保存关闭操作记录
            OrderOperateHistory history = new OrderOperateHistory();
            history.setOrderId(order.getId());
            history.setNote("批量发货");
            history.setOperateMan(username);
            history.setOrderStatus(4);
            history.setCreateTime(LocalDateTime.now());
            list.add(history);
        }
        orderOperateHistoryMapper.saveBatch(list);
        return num;
    }


}
